/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package lucene;


import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.beans.PropertyVetoException;
import java.io.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;
import java.util.logging.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.FileNameExtensionFilter;

public class SmartArchiveUI extends JFrame implements Serializable {
	
    public JDesktopPane versionsDesktopPane;
    public JDesktopPane currentVersionDesktopPane; 
    public JDesktopPane listDesktopPane;
	public JInternalFrame versionOfFilesFrame;
	public JInternalFrame currentVersionFrame;
	public JInternalFrame listFrame,versionFrame;
	public JPanel mainPanel,buttonsPanel,filterButtonsPanel,utilPanel;
	public BufferedImage logoImage;
	public Image logo;
	public ImageIcon iconLogo,iconHelp,iconUrl;
	public JLabel logoLabel,spaceLabel;
	public JSplitPane splitPane;
	public JButton openFilesButton,deleteFileButton,addUrlButton,checkButton,helpButton,aboutButton,nameButton,typeButton,dataButton,exitButton;	 
	public JScrollPane textAreaScrollPane,versionsScrollPane,versionScrollPane;
	public JScrollPane listScrollPane;
	public JList<String> listOfFiles,listOfVersions;
	public JFileChooser chooserFile;
	public File selectedFiles[];
	public File selectedDirectory;
	public DefaultListModel  filesListModel,versionsListModel;
    public JEditorPane fileContent,version ;
    public String fileName;
    public String [] types = {"html","txt","xml"};
    public int nameSortControl=1,typeSortControl=1,dataSortControl=1;
    private Graphics2D logoGraphic;
    public HashMap<Integer,String> versiuneVeche = new HashMap();
    public HashMap<Integer,String> versiuneCurenta = new HashMap();
    
	public static final long serialVersionUID = 1L;
        private IndexingProxy manager = new fileManager();
	public SmartArchiveUI() throws ClassNotFoundException {
		intitializeComponents();
	}
	
	private void intitializeComponents() throws ClassNotFoundException {
		
		
		//logoPanel
		logoImage = new BufferedImage(100,70,BufferedImage.TYPE_INT_RGB);
		try {
			logo=ImageIO.read(new File("logo3.png"));
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		logoLabel = new JLabel(new ImageIcon(logoImage));
		logoGraphic = logoImage.createGraphics();
		logoGraphic.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
		logoGraphic.setColor(new Color(58,170,207));
		logoGraphic.fillRect(0,0,100,70);
		logoGraphic.drawImage(logo,0,0,100,70,null);
		
		
		//buttonPanel 
		buttonsPanel = new JPanel();
		openFilesButton = new JButton("Add Files");
		deleteFileButton = new JButton("Delete");
		deleteFileButton.setEnabled(false);
		addUrlButton = new JButton("Add URL");	
		checkButton = new JButton("Check Files");
		helpButton = new JButton("Help");
		aboutButton = new JButton("About");
		exitButton = new JButton("Exit");
		buttonsPanel.add(openFilesButton);
		buttonsPanel.add(addUrlButton);
		buttonsPanel.add(checkButton);
		buttonsPanel.setBorder(BorderFactory.createTitledBorder("Tools"));
		buttonsPanel.setBackground(new Color(58,170,207));
		FlowLayout buttonsPanelLayout = new FlowLayout();
		buttonsPanel.setLayout(buttonsPanelLayout);
		
		//Leading Panel
		utilPanel = new JPanel();
		utilPanel.add(helpButton);
		utilPanel.add(aboutButton);
		utilPanel.add(exitButton);
		FlowLayout utilPanelLayout = new FlowLayout();
		utilPanel.setLayout(utilPanelLayout);
		utilPanel.setBorder(BorderFactory.createTitledBorder("Util"));
		utilPanel.setBackground(new Color(58,170,207));
		
		//ListScrollPane
		filterButtonsPanel = new JPanel();
		spaceLabel = new JLabel("                 ");
		nameButton = new JButton("Name A-Z");
		nameButton.setEnabled(false);
		typeButton = new JButton("Type A-Z");
		typeButton.setEnabled(false);
		dataButton = new JButton("Data <");
		dataButton.setEnabled(false);
		FlowLayout filterButtonsPanelLayout =new FlowLayout(FlowLayout.LEADING);
		filterButtonsPanel.setLayout(filterButtonsPanelLayout);
		filterButtonsPanel.add(nameButton);
		filterButtonsPanel.add(typeButton);
		filterButtonsPanel.add(dataButton);
		filterButtonsPanel.add(spaceLabel);
		filterButtonsPanel.add(deleteFileButton);
		filterButtonsPanel.setBorder(BorderFactory.createTitledBorder("  Filters"));
		filterButtonsPanel.setBackground(new Color(58,170,207));
		filterButtonsPanel.setMaximumSize(new Dimension(50,300));
		listDesktopPane = new JDesktopPane();
		listDesktopPane.setBackground(Color.LIGHT_GRAY);
		listDesktopPane.setBorder(BorderFactory.createTitledBorder("Files List"));
		listDesktopPane.setMinimumSize(new Dimension(390,300));
		listFrame = new JInternalFrame();
		listFrame.setClosable(false);
		listFrame.setVisible(true);
		listFrame.setTitle("Files List");
		listFrame.setFrameIcon(null);
		listFrame.add(filterButtonsPanel,BorderLayout.PAGE_START);
		listDesktopPane.add(listFrame);
		
        filesListModel = new DefaultListModel();
        deserialize();
        
		listOfFiles = new JList<String>(filesListModel); 
		listOfFiles.setFont(new Font("Times New Roman",Font.PLAIN,17));
		listOfFiles.setBackground(new Color(164,219,237));
        listOfFiles.setModel((ListModel<String>) filesListModel);
        
        listOfFiles.setCellRenderer(new DefaultListCellRenderer(){
        	   @Override
        	   public Component getListCellRendererComponent(JList<?> list,
        	         Object value, int index, boolean isSelected, boolean cellHasFocus) {
        	      if (value != null && !value.getClass().toString().equals("class java.lang.String")) {
        	    	 String []splits = value.toString().split("\\\\");
        	    	 String filePath = new String(splits[0]+"\\..."+"\\"+splits[splits.length-2]+"\\"+((File)value).getName());
        	         value = filePath;
        	      }
        	      return super.getListCellRendererComponent(list, value, index, isSelected,cellHasFocus);
        	   }
        	});
        
		listScrollPane = new JScrollPane(listOfFiles);
		listScrollPane.setMinimumSize(new Dimension(390,300));
		listScrollPane.setPreferredSize(new Dimension(390,500));
		listScrollPane.setBackground(new Color(97,180,207));
		listFrame.add(listScrollPane,BorderLayout.LINE_START);
		
		
		try {
			listFrame.setMaximum(true);
		} catch (PropertyVetoException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		//Current Version
		currentVersionDesktopPane = new JDesktopPane();
		currentVersionDesktopPane.setBorder(BorderFactory.createTitledBorder(""));
		currentVersionDesktopPane.setBackground(new Color(225,244,250));
		currentVersionDesktopPane.setMinimumSize(new Dimension(500,300));
        fileContent = new JEditorPane("text/html","");
        fileContent.setBackground(new Color(196,233,245));
		textAreaScrollPane = new JScrollPane(fileContent);
		
        currentVersionFrame=new JInternalFrame();
        
        currentVersionFrame.setVisible(true);
        currentVersionFrame.setClosable(true);
        currentVersionFrame.setFrameIcon(null);
        currentVersionFrame.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
        currentVersionFrame.setTitle("Current Version");
        currentVersionFrame.setResizable(true);
        
    
        currentVersionDesktopPane.add(currentVersionFrame); 
        currentVersionFrame.add(textAreaScrollPane);
        
        try {
			currentVersionFrame.setMaximum(true);
		} catch (PropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		//VersionOfFiles
		versionsDesktopPane = new JDesktopPane();
		versionsDesktopPane.setBackground(new Color(225,244,250));
		versionOfFilesFrame = new JInternalFrame();
		versionOfFilesFrame.setVisible(true);
		versionOfFilesFrame.setClosable(true);
                versionOfFilesFrame.setTitle("Versions");
		versionOfFilesFrame.setResizable(true);
		versionOfFilesFrame.setFrameIcon(null);
		versionOfFilesFrame.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
                
                versionFrame = new JInternalFrame();
		versionFrame.setVisible(true);
		versionFrame.setClosable(true);
                versionFrame.setTitle("Versions");
		versionFrame.setResizable(true);
		versionFrame.setFrameIcon(null);
		versionFrame.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
                version = new JEditorPane("text/html","");
                versionScrollPane = new JScrollPane(version);
                version.setBackground(new Color(196,233,245));
		versionFrame.add(versionScrollPane);
                
		versionsDesktopPane.setBorder(BorderFactory.createTitledBorder(""));                 
		versionsDesktopPane.setMinimumSize(new Dimension(100,300));
		versionsListModel = new DefaultListModel();
                
                listOfVersions = new JList<String>(versionsListModel); 
		listOfVersions.setFont(new Font("Times New Roman",Font.PLAIN,17));
		listOfVersions.setBackground(new Color(164,219,237));
		listOfVersions.setModel((ListModel<String>) versionsListModel);
                
                
                versionsScrollPane = new JScrollPane(listOfVersions);

		versionOfFilesFrame.add(versionsScrollPane);
		
		versionsDesktopPane.add(versionFrame);
		versionsDesktopPane.add(versionOfFilesFrame);
                
		try {
			versionOfFilesFrame.setMaximum(true);
		} catch (PropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
		
		
		//SplitPane
		splitPane = new JSplitPane();
		splitPane.setLeftComponent(currentVersionDesktopPane);
		splitPane.setRightComponent(versionsDesktopPane);
		
		
		//Asezare Componente
		mainPanel = new JPanel();
		GroupLayout mainPanelLayout = new GroupLayout(mainPanel);
		   mainPanel.setLayout(mainPanelLayout);
		   mainPanelLayout.setHorizontalGroup(
				   mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
				   .addGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
						   .addGroup(mainPanelLayout.createSequentialGroup()
								   .addComponent(buttonsPanel,GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								   .addGap(200, 250, 800)
								   .addComponent(logoLabel,GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								   .addGap(200,250,1900)
								   .addComponent(utilPanel,GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								   )
						   .addGroup(mainPanelLayout.createSequentialGroup()
								   .addComponent(listDesktopPane,400, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								   .addComponent(splitPane,0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))));
		   mainPanelLayout.setVerticalGroup(mainPanelLayout.createSequentialGroup()
				   .addGroup(mainPanelLayout.createSequentialGroup()
						   .addGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
								   .addComponent(logoLabel,70,70,70)
								   .addComponent(buttonsPanel,60, 60, 60)
								   .addComponent(utilPanel,60,60,60)
								   )
						   .addGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
								   .addComponent(listDesktopPane,GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								   .addComponent(splitPane,GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))));
		   
		//set
		iconLogo = new ImageIcon("logo2.png");
		setIconImage(iconLogo.getImage());
		setSize(1200,800);
		setVisible(true);
		setTitle("Smart Archive");
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		mainPanel.setBackground(new Color(58,170,207));
		
		//add
		add(mainPanel);
                
                
                
  
		
		//ToolTipManager
		ToolTipManager.sharedInstance().setInitialDelay(1000);
		ToolTipManager.sharedInstance().setDismissDelay(2000);
		ToolTipManager.sharedInstance().setReshowDelay(1000);
		
		//ActionListeners
		 openFilesButton.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent event) {
				 openFilesButtonActionPerformed(event);
		     }
		 });
		 
		 
		 deleteFileButton.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent event) {
				 deleteFileButtonActionPerformed(event);
			 }
		 });
		 
		 addUrlButton.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent event) {
				addUrlButtonActionPerformed(event);
		     }
		 });
		 
		 checkButton.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent event) {
				try {
					checkButtonActionPerformed(event);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		     }
		 });
		 
		 helpButton.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent event) {
				helpButtonActionPerformed(event);
		     }
		 });
		 
		 aboutButton.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent event) {
				aboutButtonActionPerformed(event);
		     }
		 });
		 
		 exitButton.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent event) {
				exitButtonActionPerformed(event);
		     }
		 });
		 
		 nameButton.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent event) {
				nameButtonActionPerformed(event);
		     }
		 });
		 
		 typeButton.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent event) {
				typeButtonActionPerformed(event);
		     }
		 });
		 
		 dataButton.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent event) {
				dataButtonActionPerformed(event);
		     }
		 });
		 
		 listOfFiles.addMouseListener(new MouseAdapter() {
			 public void mouseClicked(MouseEvent event) {
				 listOfFilesMouseClicked(event);
			 }
		 });
		 
		 listOfFiles.addMouseMotionListener(new MouseMotionAdapter() {
			 public void mouseMoved(MouseEvent event) {
				 listOfFilesMouseMoved(event);
			 }
		 });
                 
                 listOfVersions.addMouseListener(new MouseAdapter() {
			 public void mouseClicked(MouseEvent event) {
				 try {
					listOfVersionsMouseClicked(event);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 }
		 });
		  	 
		 currentVersionFrame.addInternalFrameListener(new InternalFrameAdapter() {
			 public void internalFrameClosing(InternalFrameEvent event) {
				 textAreaFrameClosing(event);
			 }
		 });
		 
		 versionOfFilesFrame.addInternalFrameListener(new InternalFrameAdapter() {
			 public void internalFrameClosing(InternalFrameEvent event) {
				 versionOfFilesFrameClosing(event);
			 }
		 });
                 
                 versionFrame.addInternalFrameListener(new InternalFrameAdapter() {
			 public void internalFrameClosing(InternalFrameEvent event) {
				 versionFrameClosing(event);
			 }
		 });
		 
		 this.addWindowStateListener(new WindowAdapter () {
			 public void windowStateChanged(WindowEvent event) {
				 frameWindowStateChanged(event);
			 }
		 });
		 
		 this.addWindowListener(new WindowAdapter () {
			 public void windowClosing(WindowEvent event) {
				 frameWindowClosed(event);
			 }
		 });
		 
		
	}
	
	//Action Listeners Functions	
	private void openFilesButtonActionPerformed(ActionEvent event) {
		chooserFile = new JFileChooser();
		chooserFile.setCurrentDirectory(new java.io.File("."));
	    chooserFile.setDialogTitle("Choose File");
	    chooserFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
	    chooserFile.setMultiSelectionEnabled(true);
	    //chooserFile.addChoosableFileFilter(new FileNameExtensionFilter("FILES","xml","txt","html"));
		chooserFile.setAcceptAllFileFilterUsed(false);
		chooserFile.setFileFilter(new FileNameExtensionFilter("FILES","xml","txt","html"));
		for(int i =0 ;i < filesListModel.size();i++)
			System.out.println(filesListModel.getElementAt(i));
		
	    if (chooserFile.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
	    	deleteFileButton.setEnabled(true);
	    	nameButton.setEnabled(true);
	    	typeButton.setEnabled(true);
	    	dataButton.setEnabled(true);
	    	selectedDirectory=chooserFile.getSelectedFile();
	    	if(selectedDirectory.isDirectory())
	    		readDirectory(selectedDirectory);
	    	else
	    		{
	    		selectedFiles = chooserFile.getSelectedFiles();
	    		boolean ok=false;
	    		for(int i=0;i<selectedFiles.length;i++) {
	    			ok=false;
	    			for(int j = 0; j < filesListModel.size() && ok==false;j++) {
	    				if(selectedFiles[i].getName().equals(filesListModel.getElementAt(j).toString().substring(filesListModel.getElementAt(j).toString().lastIndexOf("\\")+1)))
	    					ok=true;
	    			}
	    			if(ok==false) {
		    				    	    
						boolean flag;		
						String [] split;						
					//	split = selectedFiles[i].getName().split("\\.");
						File file = new File("Monitor/Resource-"+selectedFiles[i].getName());
						flag = file.mkdir();
						if(flag)
							System.out.println("created");
						
						InputStream inStream = null;
						OutputStream outStream = null;
						try{
						File source = new File(selectedFiles[i].toString());
						File destination = new File(file.toString()+"\\"+selectedFiles[i].getName());
                                                
						System.out.println("primul "+destination);
						System.out.println("al 2-lea "+selectedFiles[i].getAbsolutePath());
						System.out.println("al 3-lea  "+file.getAbsolutePath());
                                                manager.addFile(destination, selectedFiles[i].getAbsolutePath() , file.getAbsolutePath());
                                                
						inStream = new FileInputStream(source);
						outStream = new FileOutputStream(destination);
						int length;
						byte[] buffer = new byte[1024];
						while((length = inStream.read(buffer)) > 0) {
							outStream.write(buffer,0 , length);
						}
						
						inStream.close();
						outStream.close();
						filesListModel.addElement(selectedFiles[i]);
						}catch(IOException e){
				    	    e.printStackTrace();
				    	}
	    			}
	    		}
                    
	    	}    			
	    }
	}
		
	private void deleteFileButtonActionPerformed(ActionEvent event) {
		int [] indices;
		Object string;
		File file;
		String path;
		indices = listOfFiles.getSelectedIndices();
		String []parts;
		for(int i = indices.length-1;i >=0;i--) {
			if(filesListModel.getElementAt(indices[i]).toString().matches("URL.*")) {
				parts = filesListModel.getElementAt(indices[i]).toString().split("URL :http://");
				System.out.println(parts[1]);
				path = new String("Monitor\\Resource-"+parts[1]);
				System.out.println("prima "+path);
				file = new File(path);
				deleteDirectory(file);
				
				manager.removeFile(new File(filesListModel.getElementAt(indices[i]).toString()));
				filesListModel.remove(indices[i]);
			}
			else {
				file =  (File) filesListModel.getElementAt(indices[i]);	

				path = new String("Monitor\\Resource-"+file.getName());
				System.out.println("a 2-a "+path);
				file = new File(path);
				deleteDirectory(file);
				
				System.out.println("indice "+indices[i]);
				System.out.println(filesListModel.getElementAt(indices[i]).toString());
				manager.removeFile(new File(filesListModel.getElementAt(indices[i]).toString()));
				filesListModel.remove(indices[i]);	
				
		
			}
		}
		
		
		
		int size = filesListModel.getSize();
		if(size == 0) {
			deleteFileButton.setEnabled(false);
			nameButton.setEnabled(false);
	    	typeButton.setEnabled(false);
	    	dataButton.setEnabled(false);
		}		
	}
	
	private void addUrlButtonActionPerformed(ActionEvent event) {	
		final JFrame frame = new JFrame();
		frame.setVisible(true);
		iconUrl = new ImageIcon("url.png");
		frame.setIconImage(iconUrl.getImage());
		final DefaultListModel urlListModel = new DefaultListModel();
		final JList listOfUrls = new JList<String>(urlListModel);
		listOfUrls.setModel((ListModel<String>)urlListModel);
		JScrollPane urlScrollPane = new JScrollPane(listOfUrls);
		JPanel urlPanel = new JPanel();
		JButton okButton = new JButton("Ok");
		final JTextArea textArea = new JTextArea(1,10);
		JLabel label = new JLabel(" OR ");
		urlPanel.add(okButton,BorderLayout.LINE_START);
		urlPanel.add(textArea,BorderLayout.PAGE_END);
		urlPanel.add(label);
		urlPanel.add(urlScrollPane,BorderLayout.CENTER);
		frame.setSize(500,this.getHeight());
		frame.add(urlPanel);
		frame.pack();
		try {                         
            BufferedReader bufferedReader = new BufferedReader(new FileReader("urlFile.txt"));
            String textLine = bufferedReader.readLine();
            
            while(textLine != null){
                 
                 urlListModel.addElement(textLine);
                 textLine = bufferedReader.readLine();
            System.out.println(urlListModel.size());     
            }          
			} catch (FileNotFoundException ex) {
            System.out.println("Error file not found");
			} catch (IOException ex) {
            System.out.println("Error IO exception ");
			}
		okButton.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent event) {
				ArrayList<String> urls = new ArrayList<String>();
				int index = listOfUrls.getSelectedIndex();
				int var=0;
				if(index == -1 && textArea.getText()==null)
					frame.dispose();
				else {
					deleteFileButton.setEnabled(true);
					nameButton.setEnabled(true);
			    	typeButton.setEnabled(true);
			    	dataButton.setEnabled(true);
			    	if(index != -1)
					for(int i = 0; i < urlListModel.getSize(); i++)
						if(listOfUrls.isSelectedIndex(i)) {
							urls.add((String) urlListModel.getElementAt(i));
							var++;
						}
			    	if(!textArea.getText().isEmpty()) {
			    		urls.add("http://"+textArea.getText());
			    		System.out.println("asd");
						try {
							BufferedWriter bufferedWriter = new BufferedWriter (new FileWriter("urlFile.txt",true));

							bufferedWriter.write("\nhttp://"+textArea.getText());
							
							bufferedWriter.flush();
							bufferedWriter.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}		    		
			    	}
				}
				
				String []parts;
				String []split;
				File file;
				boolean ok=false;
				for(int i = 0; i< urls.size();i++) {
					ok=false;
					for(int j = 0; j < filesListModel.size(); j++) {
						if(filesListModel.getElementAt(j).toString().matches("URL.*")) {		
							split = filesListModel.getElementAt(j).toString().split("URL :");
							if(urls.get(i).equals(split[1]))
								ok=true;
						}
					}
					if(ok==false) {
						try {
							filesListModel.addElement("URL :" + urls.get(i));
							parts = urls.get(i).split("http://");	
							file = new File("Monitor/Resource-"+parts[1]);
							file.mkdir();
							file = new File("Monitor/Resource-"+parts[1]+"/"+parts[1]+".html");		
							
							OutputStream out = new FileOutputStream("Monitor/Resource-"+parts[1]+"/"+parts[1]+".html");

					        URL url = new URL(urls.get(i));
					        URLConnection conn = url.openConnection();
					        conn.connect();
					        InputStream is = conn.getInputStream();

					        copy(is, out);
					        is.close();
					        out.close();
					        manager.addFile(file, urls.get(i), file.getAbsolutePath().toString().substring(0, file.getAbsolutePath().toString().lastIndexOf("\\")));
			           } catch (MalformedURLException me) {
			                     System.out.println(me); 
	
			           } catch (IOException ioe) {
			        	   		fileContent.setText(ioe.toString());
			                    System.out.println(ioe);	                    
			           }			
					}
				}
				frame.dispose();
		     }
			
		 });
		
	}
	
	private void copy(InputStream from, OutputStream to) throws IOException {
        byte[] buffer = new byte[4096];
        while (true) {
            int numBytes = from.read(buffer);
            if (numBytes == -1) {
                break;
            }
            to.write(buffer, 0, numBytes);
        }
    }
	
	public void checkButtonFunction() throws FileNotFoundException, IOException {
		System.out.println("functie");
		manager.checkFiles();
	}
	
	private void checkButtonActionPerformed(ActionEvent event) throws FileNotFoundException, IOException {
		System.out.println("ai apasat");
		checkButtonFunction();
	}
	
	
	private void helpButtonActionPerformed(ActionEvent event) {
		JFrame frame = new JFrame();
		frame.setVisible(true);
		frame.setSize(350,this.getHeight());
		iconHelp = new ImageIcon("help2.png");
		frame.setIconImage(iconHelp.getImage());
		System.out.println(this.getWidth());
		frame.setLocation(this.getWidth()-350, 0);
		JEditorPane editorPane = new JEditorPane("text/html","");
		editorPane.setBackground(new Color(253,255,180));
		JScrollPane scrollPane = new JScrollPane(editorPane);	
		frame.add(scrollPane);
		try {                         
            BufferedReader bufferedReader = new BufferedReader(new FileReader("help.txt"));
            String textLine = bufferedReader.readLine();
            StringBuilder stringBuilder = new StringBuilder();
            
            while(textLine != null){           
                stringBuilder.append(textLine+"\n");               
                textLine = bufferedReader.readLine();              
            }        
            editorPane.setText(stringBuilder.toString());
            editorPane.setEditable(false);
            bufferedReader.close();		           
        } catch (FileNotFoundException ex) {
           System.out.println("Eroare 22");
        } catch (IOException ex) {
            Logger.getLogger(SmartArchiveUI.class.getName()).log(Level.SEVERE, null, ex);
        }
	}
	
	private void aboutButtonActionPerformed(ActionEvent event) {
		JFrame frame = new JFrame();
		 try {                         
	            BufferedReader bufferedReader = new BufferedReader(new FileReader("about.txt"));
	            String textLine = bufferedReader.readLine();
	            StringBuilder stringBuilder = new StringBuilder();
	            
	            while(textLine != null){           
	                stringBuilder.append(textLine+"\n");               
	                textLine = bufferedReader.readLine();              
	            }            
	            JOptionPane.showMessageDialog(frame,stringBuilder);
	            bufferedReader.close();		           
	        } catch (FileNotFoundException ex) {
	           System.out.println("Eroare 22");
	        } catch (IOException ex) {
	            Logger.getLogger(SmartArchiveUI.class.getName()).log(Level.SEVERE, null, ex);
	        }
		
	}
	
	private void exitButtonActionPerformed(ActionEvent event) {	
		serialize();
		System.exit(0);
	}
	
	private void nameButtonActionPerformed(ActionEvent event) {		
		nameSortControl=1-nameSortControl;
		File file;
		ArrayList<String> urlList = new ArrayList<String>();
		ArrayList<String> filesList = new ArrayList<String>();
		ArrayList<String> filesPathList = new ArrayList<String>();
		for(int i = 0; i < filesListModel.getSize(); i++) {
			if(filesListModel.getElementAt(i).toString().matches("URL.*"))
				urlList.add(filesListModel.getElementAt(i).toString());
			else {
				file = (File) filesListModel.getElementAt(i);
				filesList.add(file.getName());
				filesPathList.add(file.toString());
			}
				
		}
		System.out.println(filesList.size());
		for(int i = 0; i < filesList.size(); i++)
			System.out.println(filesList.get(i));
		if(nameSortControl==0) {
			Collections.sort(urlList,String.CASE_INSENSITIVE_ORDER);
			Collections.sort(filesList,String.CASE_INSENSITIVE_ORDER);
			nameButton.setText("Name Z-A");
		}
		else {
			Collections.reverse(urlList);
			Collections.reverse(filesList);
			nameButton.setText("Name A-Z");
		}
		System.out.println(filesList.size());
		for(int i = 0; i < filesList.size(); i++)
			System.out.println(filesList.get(i));
		filesListModel.removeAllElements();
		for(int i = 0; i < urlList.size(); i++)
			filesListModel.addElement(urlList.get(i));
		int ok;
		for(int i =0;i < filesList.size();i++){
		ok=0;
			for(int j = 0;j < filesList.size() && ok==0;j++) {
				if(filesPathList.get(j).matches(".*\\\\"+filesList.get(i))) {
					File temp = new File(filesPathList.get(j));
					filesListModel.addElement(temp);
					ok=1;
				}
			}
		}
	
	}
	
	private void typeButtonActionPerformed(ActionEvent event) {
		typeSortControl = 1 - typeSortControl;
		ArrayList<String> urlList = new ArrayList<String>();
		ArrayList<String> filesList = new ArrayList<String>();
		for(int i = 0; i < filesListModel.getSize(); i++) {
			if(filesListModel.getElementAt(i).toString().matches("URL.*"))
				urlList.add(filesListModel.getElementAt(i).toString());
			else {
				filesList.add(filesListModel.getElementAt(i).toString());
			}
		}
		
		if(typeSortControl==0) {
			Arrays.sort(types);
			typeButton.setText("Type Z-A");
		}
		else {
			Arrays.sort(types,Collections.reverseOrder());
			typeButton.setText("Type A-Z");
		}
		filesListModel.removeAllElements();
		
		for(int i = 0; i < urlList.size(); i++)
			filesListModel.addElement(urlList.get(i));
		
		for(int i = 0; i < types.length; i++)
		for(int j = 0; j < filesList.size(); j++)
			if(filesList.get(j).matches(".*"+types[i])) {
				File temp = new File(filesList.get(j));
				filesListModel.addElement(temp);
			}	
	}
	
	private void dataButtonActionPerformed(ActionEvent event) {
		dataSortControl = 1 - dataSortControl;
		File temp;
		ArrayList<String> urlList = new ArrayList<String>();
		ArrayList<File> filesList = new ArrayList<File>();
		for(int i = 0; i < filesListModel.getSize(); i++) {
			if(filesListModel.getElementAt(i).toString().matches("URL.*"))
				urlList.add(filesListModel.getElementAt(i).toString());
			else {
				filesList.add((File) filesListModel.getElementAt(i));
			}
		}
		if(dataSortControl == 0)
			dataButton.setText("Data >");
		else
			dataButton.setText("Data <");
		
		for(int i = 0; i < filesList.size()-1; i++)
			for(int j = 0; j < filesList.size()-i-1; j++)
				if(dataSortControl == 0) {				
					if(filesList.get(j).lastModified()<filesList.get(j+1).lastModified()) {
						temp = filesList.get(j);
						filesList.set(j, filesList.get(j+1));
						filesList.set(j+1, temp);
					}
				}
				else {				
					if(filesList.get(j).lastModified()>filesList.get(j+1).lastModified()) {
						temp = filesList.get(j);
						filesList.set(j, filesList.get(j+1));
						filesList.set(j+1, temp);
					}
				}
		filesListModel.removeAllElements();
		
		for(int i = 0; i < urlList.size(); i++)
			filesListModel.addElement(urlList.get(i));
		
		for(int i = 0; i < filesList.size(); i++)
			filesListModel.addElement(filesList.get(i));
	}
	
	private void listOfFilesMouseMoved(MouseEvent event) {
	
		int index = listOfFiles.locationToIndex(event.getPoint());
		if(index > -1) 
		listOfFiles.setToolTipText(filesListModel.getElementAt(index).toString());
	}
	
	private void listOfFilesMouseClicked (MouseEvent event) {
		int index;			
		if(event.getClickCount() == 2 && listOfFiles.getSelectedIndex() !=-1) {		
			index = listOfFiles.getSelectedIndex();
	        fileName = filesListModel.getElementAt(index).toString();
                File name = new File(fileName);
                String []splitExtension = name.getName().split("\\.");
	        if(fileName.matches("URL :.*") == false) {
                       
                        
		        try {                  
                            System.out.println(fileName);
		            BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
		            String textLine = bufferedReader.readLine();
		            StringBuilder stringBuilder = new StringBuilder();
		             if(splitExtension[splitExtension.length-1].equals("html") || splitExtension[splitExtension.length-1].equals("xml")) {
                                 stringBuilder.append("<xmp>");
                                 System.out.println(splitExtension[splitExtension.length-1]);
                             }
                             System.out.println(splitExtension[splitExtension.length-1]);
		            while(textLine != null){  
                                if(splitExtension[splitExtension.length-1].equals("html") || splitExtension[splitExtension.length-1].equals("xml")) {
                                    stringBuilder.append(textLine+"\n");
                                } else {
		                stringBuilder.append(textLine+"<br>");
                                }
		                textLine = bufferedReader.readLine();              
		            }  
		            File file = new File(fileName);
		            currentVersionFrame.setTitle(file.getName());
		            currentVersionFrame.setVisible(true);
		            versionOfFilesFrame.setVisible(true);
                            if(splitExtension[splitExtension.length-1].equals("html") || splitExtension[splitExtension.length-1].equals("xml")) {
                                 stringBuilder.append("</xmp>");
                             }
                            System.out.println(stringBuilder.toString());
		            splitPane.setRightComponent(versionsDesktopPane);
		           	fileContent.setText(stringBuilder.toString());
		            bufferedReader.close();		           
		        } catch (FileNotFoundException ex) {
		           System.out.println("Eroare 22");
		        } catch (IOException ex) {
		            Logger.getLogger(SmartArchiveUI.class.getName()).log(Level.SEVERE, null, ex);
		        }
                        
                        versionsListModel.removeAllElements();
                      
		        File file = new File("Monitor/Resource-"+name.getName());
                        String files[] = file.list();
		        for(int i = 0 ; i < files.length-2; i++) {
		        	versionsListModel.addElement(files[i]+"/"+name.getName());
		        }
	        }
	        else
	        	{
	            String[] parts;
	            parts = fileName.split("URL :");            
	            String part = parts[1];
	            System.out.println(part);	            
	             try {
	            	 currentVersionFrame.setVisible(true);
			         versionOfFilesFrame.setVisible(true);
			         splitPane.setRightComponent(versionsDesktopPane);
	                 URL archive = new URL(part);
	                 currentVersionFrame.setTitle(part);
	                 BufferedReader in = new BufferedReader(new InputStreamReader(archive.openStream()));
	                 String inputLine;
	                 StringBuilder content = new StringBuilder();
	                 while ((inputLine = in.readLine()) != null) {
	                 content.append(inputLine + "\n");
	                 inputLine = in.readLine();
	                 }                        
	                 fileContent.setText(content.toString());
	                 in.close(); 
	           } catch (MalformedURLException me) {
	                     System.out.println(me); 

	           } catch (IOException ioe) {
	        	   		fileContent.setText(ioe.toString());
	                     System.out.println(ioe);
	           }
	        }
		}
	}
        
        private void listOfVersionsMouseClicked(MouseEvent event) throws IOException {
		int index;
		if(event.getClickCount() == 2 && listOfVersions.getSelectedIndex() !=-1) {
			index = listOfVersions.getSelectedIndex();
			String element = (String) versionsListModel.getElementAt(index);
			File name = new File(fileName);
			System.out.println(element+"element");
	        File file = new File("Monitor/Resource-"+name.getName()+"/"+element);
			
            String split[] = element.split("/");
            //version.setText(stringBuilder.toString());

            
            File zipPath = new File ("Monitor/Resource-"+name.getName()+"/"+split[split.length-2]+"/temp");
            File rarFile = new File("Monitor/Resource-"+name.getName()+"/"+split[split.length-2]+"/"+split[split.length-2]+".zip");
            System.out.println(rarFile);
            ZipFile zipFile = null;
            try {
                zipFile = new ZipFile(rarFile);
                // get an enumeration of the ZIP file entries
                Enumeration<ZipEntry> e = (Enumeration<ZipEntry>) zipFile.entries();
                while (e.hasMoreElements()) {
                    ZipEntry entry = e.nextElement();
                    //System.out.println("Entry: " + e.nextElement().getName());
                    File destinationPath = new File(zipPath, entry.getName());
                    System.out.println("Path-ul: " + zipPath);
                    System.out.println("Numele: " + entry.getName());

                    //create parent directories
                    destinationPath.getParentFile().mkdirs();
                    // if the entry is a file extract it
                    if (entry.isDirectory()) {
                        continue;
                    }
                    else { 
                        if(entry.getName().matches("versiuneCurenta") || entry.getName().matches("versiuneVeche")) {
                            System.out.println("Extracting file: " + destinationPath);
                            BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                            int b;
                            byte buffer[] = new byte[1024];
                            FileOutputStream fos = new FileOutputStream(destinationPath);
                            BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);
                            while ((b = bis.read(buffer, 0, 1024)) != -1) {
                                bos.write(buffer, 0, b);
                            }
                            bos.close();
                            bis.close();
                        }
                    }

                }
            }
                catch (IOException ioe) {
                    System.out.println("Error opening zip file" + ioe);
                }
                 finally {
                     try {
                         if (zipFile!=null) {
                             zipFile.close();
                         }
                     }
                     catch (IOException ioe) {
                            System.out.println("Error while closing zip file" + ioe);
                     }
                 }
            
            try 
             { 
                 FileInputStream fileInputStream = new FileInputStream("Monitor/Resource-"+name.getName()+"/"+split[split.length-2]+"/temp/versiuneVeche"); 
                 ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); 
                 versiuneVeche =  (HashMap<Integer, String>) objectInputStream.readObject();
                  
                 objectInputStream.close(); 
                 } 
                 catch(Exception e) { 
                 System.out.println("Exception during serialization: " + e); 
                 System.exit(0); 
             } 
        	 
        	 try 
             { 
                 FileInputStream fileInputStream = new FileInputStream("Monitor/Resource-"+name.getName()+"/"+split[split.length-2]+"/temp/versiuneCurenta"); 
                 ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); 
                 versiuneCurenta = (HashMap<Integer, String>) objectInputStream.readObject();
                 
                 objectInputStream.close(); 
                 } 
                 catch(Exception e) { 
                 System.out.println("Exception during serialization: " + e); 
                 System.exit(0); 
             } 
            System.out.println(versiuneVeche+"hehe");
            System.out.println(versiuneCurenta+"haha");
            deleteDirectory(zipPath);
            
            StringBuilder original = new StringBuilder();
            StringBuilder versionStringBuilder = new StringBuilder();
            File originalPath = new File ("Monitor/Resource-"+name.getName()+"/"+name.getName());
            File versionPath = new File("Monitor/Resource-"+name.getName()+"/"+split[split.length-2]+"/"+name.getName());
            
            BufferedReader bufferedReaderO = new BufferedReader(new FileReader(originalPath));
            BufferedReader bufferedReader = new BufferedReader(new FileReader(versionPath));
            String textLineO = bufferedReaderO.readLine();
            String textLine = bufferedReader.readLine();
            StringBuilder currentVersionStringBuilder = new StringBuilder();
            
            String []splitExtension = name.getName().split("\\.");
            System.out.println("split"+splitExtension[splitExtension.length-1]);
            
             if(splitExtension[splitExtension.length-1].equals("html") || splitExtension[splitExtension.length-1].equals("xml")) {
                 versionStringBuilder.append("<xmp>");
                 currentVersionStringBuilder.append("<xmp>");
             }
            int position1 = 0 ,position2 = 0;
            while(textLine != null){
                int ok = 1, ok2 = 1;
                position2++;
                String splitLine[] = textLine.split(" ");
               
                for(int i = 0 ; i < splitLine.length; i++){
                    ok=1;
                     if(splitLine.length>1) {
                        position2++;
                    }
                    if(splitLine[i].contains("-")) {
                            String splitSplit[] = splitLine[i].split("-");
                            for(int j = 0 ; j < splitSplit.length; j++){
                                ok2 = 1;
                                for(Map.Entry< Integer,String> entry : versiuneVeche.entrySet()) {
                                    System.out.println(splitSplit[j]+entry.getValue());
                                    if(splitSplit[j].toLowerCase().matches(entry.getValue()) && ok2 == 1) {
                                        ok2 = 0;
                                        versionStringBuilder.append("<font style=\"background-color: yellow;\">"+splitSplit[j]+"</font>");
                                    }
                                }
                                if(ok2==0) {
                                    versionStringBuilder.append("-");
                                }
                            }
                        } else {
                    
                        for(Map.Entry< Integer,String> entry : versiuneVeche.entrySet()) {

                            if(splitLine[i].replaceAll("[,.:;<>]", "").toLowerCase().matches(entry.getValue()) && ok==1 && entry.getKey()>=position2-2 && entry.getKey()<=position2 ) {
                                System.out.println("1"+splitLine[i]+position2);
                                ok=0;
                                versionStringBuilder.append("<font style=\"background-color: yellow;\">"+splitLine[i]+"</font>"+" ");
                            } 


                        }
                    }
                    if(ok!=0 && ok2!=0) {
                    System.out.println("2"+splitLine[i]);
                            versionStringBuilder.append(splitLine[i]+" ");
                    }
                }
                versionStringBuilder.append("<br>");
                textLine = bufferedReader.readLine();
                
            }
            
            
            
            
            while(textLineO != null){
                int ok = 1, ok2 = 1;
                String splitLine[] = textLineO.split(" ");
                for(int i = 0 ; i < splitLine.length; i++){
                    ok=1;
                    
                    if(splitLine.length>1) {
                        position1++;
                    }
                    if(splitLine[i].contains("-")) {
                            String splitSplit[] = splitLine[i].split("-");
                            for(int j = 0 ; j < splitSplit.length; j++){
                                ok2 = 1;
                                for(Map.Entry< Integer,String> entry : versiuneCurenta.entrySet()) {
                                    System.out.println(splitSplit[j]+entry.getValue());
                                    if(splitSplit[j].toLowerCase().matches(entry.getValue()) && ok2 == 1) {
                                        ok2 = 0;
                                        currentVersionStringBuilder.append("<font style=\"background-color: yellow;\">"+splitSplit[j]+"</font>");
                                    }
                                }
                                if(ok2==0) {
                                    currentVersionStringBuilder.append("-");
                                }
                            }
                        } else {
                    
                        for(Map.Entry< Integer,String> entry : versiuneCurenta.entrySet()) {

                            if(splitLine[i].replaceAll("[,.:;<>]", "").toLowerCase().matches(entry.getValue()) && ok==1 && entry.getKey()>=position1-2 && entry.getKey()<=position1 ) {
                                System.out.println("1"+splitLine[i]+position1);
                                ok=0;
                                currentVersionStringBuilder.append("<font style=\"background-color: yellow;\">"+splitLine[i]+"</font>"+" ");
                            } 


                        }
                    }
                    if(ok!=0 && ok2!=0) {
                    System.out.println("2"+splitLine[i]);
                            currentVersionStringBuilder.append(splitLine[i]+" ");
                    }
                }
                currentVersionStringBuilder.append("<br>");
                textLineO = bufferedReaderO.readLine();
                
            }
            
            
            
            
            bufferedReader.close();
            bufferedReaderO.close();

            fileContent.setText(currentVersionStringBuilder.toString());
            version.setText(versionStringBuilder.toString());
            
                        versionFrame.setTitle("Version no. "+split[split.length-2]+" of "+split[split.length-1]);
            try {
				versionFrame.setMaximum(true);
			} catch (PropertyVetoException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			        
		}
            
            
            }
            
	}
	
	
	private void textAreaFrameClosing(InternalFrameEvent event) {
		currentVersionFrame.setVisible(false);	
		versionOfFilesFrame.setVisible(false);
		if(currentVersionFrame.isVisible()==false) {
			listOfFiles.setSelectedIndex(-1);
        	listOfFiles.ensureIndexIsVisible(-1);    	
		}
	}
	
	private void versionOfFilesFrameClosing(InternalFrameEvent event) {
		splitPane.remove(versionsDesktopPane);
		
	}
        
        private void versionFrameClosing(InternalFrameEvent event) {
		versionFrame.setMaximizable(false);
		try {
			versionOfFilesFrame.setMaximum(true);
		} catch (PropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("ceplm");
	}
	
	private void frameWindowStateChanged(WindowEvent event) {
		if((event.getOldState() & this.MAXIMIZED_BOTH) == 0 && (event.getNewState() & this.MAXIMIZED_BOTH) != 0) {
			currentVersionDesktopPane.setMinimumSize(new Dimension(800,300));
		} 
		else if ((event.getOldState() & this.MAXIMIZED_BOTH) != 0 && (event.getNewState() & this.MAXIMIZED_BOTH) == 0) {
			currentVersionDesktopPane.setMinimumSize(new Dimension(500,300));
			versionsDesktopPane.setMinimumSize(new Dimension(275,300));
		}	
	}
        
        
	
	private void frameWindowClosed(WindowEvent event) {
		serialize();
		System.exit(0);
	}
	
	private void readDirectory(File directory) {
		File [] directoryFiles = directoryFiles = directory.listFiles(); 
		String [] files = directory.list();
		boolean ok=false;
		for(int i=0;i < files.length;i++) {
			if(directoryFiles[i].isDirectory())
				readDirectory(directoryFiles[i]);
			else {
				ok=false;
				for(int j=0; j < filesListModel.size(); j++) {
					if(("Monitor\\Resource-"+directoryFiles[i].getName()).equals(filesListModel.getElementAt(j).toString().substring(0, filesListModel.getElementAt(j).toString().lastIndexOf("\\"))))
						ok=true;
				}
				if(files[i].matches(".*txt") || files[i].matches(".*html") || files[i].matches(".*xml")) {
					if(ok==false) {
						
						boolean flag;		
						String [] split;						
					//	split = directoryFiles[i].getName().split("\\.");
						File file = new File("Monitor/Resource-"+files[i]);
						flag = file.mkdir();
						if(flag)
							System.out.println("created");
						
                        InputStream inStream = null;
						OutputStream outStream = null;
						try{
							File source = new File(directoryFiles[i].toString());
							File destination = new File(file.toString()+"\\"+directoryFiles[i].getName());
							System.out.println("index "+i);
							System.out.println("primul "+destination);
							System.out.println("al 2-lea "+directoryFiles[i].getAbsolutePath());
							System.out.println("al 3-lea  "+destination);
                                                        manager.addFile(destination, directoryFiles[i].getAbsolutePath() , file.getAbsolutePath());
							inStream = new FileInputStream(source);
							outStream = new FileOutputStream(destination);
							int length;
							byte[] buffer = new byte[1024];
							while((length = inStream.read(buffer)) > 0) {
								outStream.write(buffer,0,length);
							}				
							inStream.close();
							outStream.close();		
							filesListModel.addElement(destination);	
						}catch(IOException e){
				    	    e.printStackTrace();
				    	}	
					}
				}	
			}				
		}		
	}
	
	private void deleteDirectory(File file) {
		if(!file.exists())
			return;
		if(file.isDirectory()) {
			for(File f : file.listFiles()) {
				deleteDirectory(f);
			}
		}
		file.delete();
	}
	
	private void serialize() {
         //   serialize_manager();
            try 
            { 
                FileOutputStream fileOutputStream = new FileOutputStream("manager"); 
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); 
                objectOutputStream.writeObject(manager); 
                objectOutputStream.flush(); 
                objectOutputStream.close(); 
                } 
                catch(Exception e) { 
                System.out.println("Exception during serialization: " + e); 
                System.exit(0); 
            } 
            
            
            try 
            { 
                FileOutputStream fileOutputStream = new FileOutputStream("serial"); 
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); 
                objectOutputStream.writeObject(filesListModel); 
                objectOutputStream.flush(); 
                objectOutputStream.close(); 
                } 
                catch(Exception e) { 
                System.out.println("Exception during serialization: " + e); 
                System.exit(0); 
            } 
	}
	
        private void serialize_manager()
        {
            try 
            { 
                FileOutputStream fileOutputStream = new FileOutputStream("manager"); 
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); 
                objectOutputStream.writeObject(manager);
                objectOutputStream.flush(); 
                objectOutputStream.close(); 
                } 
                catch(Exception e) { 
                System.out.println("Exception during serialization of manager: " + e); 
                System.exit(0); 
            } 
        }
        
        private void deserialize_manager() throws ClassNotFoundException 
        {
            try
            {
               FileInputStream fileIn = new FileInputStream("manager");
               ObjectInputStream in = new ObjectInputStream(fileIn);
               fileManager manager1 = null;
               manager1 = (fileManager)in.readObject();
               in.close();
               fileIn.close();
            }
            catch(IOException i)
            {
               i.printStackTrace();
               return;
            }
            
        }
        
	private void deserialize() throws ClassNotFoundException 
        {
			try
	        {
	           FileInputStream fileIn = new FileInputStream("manager");
	           ObjectInputStream in = new ObjectInputStream(fileIn);
	          // fileManager manager1 = null;
	           manager = (fileManager)in.readObject();
	           in.close();
	           fileIn.close();
	           
	        }
	        catch(IOException i)
	        {
	           i.printStackTrace();
	           return;
	        }
			
			
            try 
            { 
                int size;
                Object object[];
                FileInputStream fileInputStream = new FileInputStream("serial"); 
                ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
                filesListModel = (DefaultListModel) objectInputStream.readObject();
                
               System.out.println(filesListModel.size());
                if(filesListModel.size()!=0) {
                   deleteFileButton.setEnabled(true);
	                nameButton.setEnabled(true);
	                typeButton.setEnabled(true);
	                dataButton.setEnabled(true);
	                fileInputStream.close();
	                objectInputStream.close(); 
                }
             } 
             catch(Exception e) { 
                System.out.println("Exception during deserialization: " + e); 
                System.exit(0); 
                } 	
            }
			

}